package com.yylending.las.lending.quota.baseinfo;

import android.content.Context;
import android.text.TextUtils;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yyfax.common.CLog;
import com.yyfax.infrastructure.eventbus.EventAgent;
import com.yyfax.infrastructure.mvp.Model;
import com.yyfax.infrastructure.network.NetworkHelper;
import com.yyfax.infrastructure.network.entity.BaseResultEntity;
import com.yyfax.infrastructure.network.entity.EmptyEntity;
import com.yylending.las.Global;
import com.yylending.las.YJKD;
import com.yylending.las.common.AESEntity;
import com.yylending.las.common.utils.area.AddressCityBean;
import com.yylending.las.common.utils.area.AddressDistrictBean;
import com.yylending.las.common.utils.area.AddressProvinceBean;
import com.yylending.las.common.utils.preferenceutils.PreferenceConstants;
import com.yylending.las.lending.quota.entity.PersonalBean;
import com.yylending.las.lending.quota.initdata.InitDataModel;
import retrofit2.http.Body;
import retrofit2.http.Header;
import retrofit2.http.POST;
import rx.Observable;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by laixj on 2017/6/19.
 * Copyright ©2016 www.yylending.com. All Rights Reserved.
 */
public class BaseInfoModel extends Model {
	public final static String TAG = BaseInfoModel.class.getSimpleName();

	public final static int METHOD_SAVE_BASE_INFO = 0;
	public final static int METHOD_GET_SUPPORT_AREA = 2;

	@Override
	public Observable getObservable(Object params, int functionalCode) {
		Service service = (Service) NetworkHelper.createService(Service.class);
		switch (functionalCode) {
			case METHOD_SAVE_BASE_INFO:
				return service.saveBaseInfo(Global.LOGIN_TOKEN, (AESEntity) params);
			case METHOD_GET_SUPPORT_AREA:
				return service.getSupportAreaList(Global.LOGIN_TOKEN, new EmptyEntity());
		}
		return null;
	}

	@Override
	public void onNext(Object entity) {
		CLog.i(TAG, "onNext: " + entity.toString());
		BaseResultEntity result = cast(entity);
		switch (result.requestCode) {
			case METHOD_SAVE_BASE_INFO:
				SaveInfoResult saveInfoResult = cast(entity);
				EventAgent.post(saveInfoResult);
				break;
			case METHOD_GET_SUPPORT_AREA:
				AreaResult areaResult = cast(entity);
				EventAgent.post(areaResult);
				break;
		}
	}

	private interface Service {
		/**
		 * 保存基本信息接口
		 */
		@POST("server/customer/saveInfo")
		Observable<SaveInfoResult> saveBaseInfo(@Header("token") String token, @Body AESEntity params);
		/**
		 * 常住地区接口
		 */
		@POST("server/params/getAccessCity")
		Observable<AreaResult> getSupportAreaList(@Header("token") String token, @Body EmptyEntity params);
	}

	static class SaveInfoResult extends BaseResultEntity<String> {
	}

	static class AreaResult extends BaseResultEntity<AccessCityList> {
	}

	static class AccessCityList {
		public List<AccessCity> cities = new ArrayList<>();
	}

	public static class AccessCity {
		public String code = "";
		public List<String> children = new ArrayList<>();

		@Override
		public String toString() {
			return "AccessCity{" +
					"code='" + code + '\'' +
					", children=" + children +
					'}';
		}
	}

	public static void saveBaseInfoLocal(PersonalBean baseInfo) {
		Gson gson = new Gson();
		String baseInfoStr = gson.toJson(baseInfo, PersonalBean.class);
		CLog.i(TAG, "baseInfoStr=" + baseInfoStr);
		YJKD.getInstance().getPreferenceManager().savePreference(PreferenceConstants.KEY_BASE_INFO, baseInfoStr);
	}

	public static PersonalBean getBaseInfoLocal() {
		PersonalBean bean = null;
		String baseInfo = YJKD.getInstance().getPreferenceManager().getBaseInfo();
		if (!TextUtils.isEmpty(baseInfo) && !"{}".equals(baseInfo)) {
			CLog.i(TAG, "原有信息-->" + baseInfo);
			Gson gson = new Gson();
			bean = gson.fromJson(baseInfo, PersonalBean.class);
		}
		return bean;
	}

	private void initCityAndDistrict(ArrayList<AddressProvinceBean> mProvince, ArrayList<ArrayList<AddressCityBean>> mCity,
			ArrayList<ArrayList<ArrayList<AddressDistrictBean>>> mDistrict) {
		for (AddressProvinceBean province : mProvince) {
			ArrayList<AddressCityBean> cityList = new ArrayList<>();
			ArrayList<ArrayList<AddressDistrictBean>> districtList = new ArrayList<>();
			for (AddressCityBean city : province.getCities()) {
				cityList.add(city);
				ArrayList<AddressDistrictBean> districtList1 = new ArrayList<>();
				for (AddressDistrictBean district : city.getCounties()) {
					districtList1.add(district);
				}
				districtList.add(districtList1);
			}
			mCity.add(cityList);
			mDistrict.add(districtList);
		}
		CLog.i(TAG, "准入省份=" + mProvince.toString());
		CLog.i(TAG, "准入城市=" + mCity.toString());
		CLog.i(TAG, "准入地区=" + mDistrict.toString());
	}

	public void getAccessAddress(Context context, List<AccessCity> areaList, ArrayList<AddressProvinceBean> mProvince,
			ArrayList<ArrayList<AddressCityBean>> mCity, ArrayList<ArrayList<ArrayList<AddressDistrictBean>>> mDistrict) {
		CLog.i(TAG, "准入城市tempList=开始");
		String addressJsonStr = readLocalJson(context.getApplicationContext(), "area.txt");
		CLog.i(TAG, "准入城市读取文件");
		if (null == areaList || areaList.size() == 0) {
			return;
		}
		try {
			List<AddressProvinceBean> tempList = new Gson().fromJson(addressJsonStr, new TypeToken<List<AddressProvinceBean>>() {
			}.getType());
			CLog.i(TAG, "准入城市tempList=" + tempList.toString());
			CLog.i(TAG, "准入城市areaList=" + areaList.toString());
			for (AccessCity city : areaList) {
				AddressProvinceBean province1 = new AddressProvinceBean();
				for (AddressProvinceBean province : tempList) {
					if (city.code.equals(province.getAreaId())) {//开放省份
						List<AddressCityBean> cityList1 = new ArrayList<>();
						for (AddressCityBean cityBean : province.getCities()) {
							if (city.children.contains(cityBean.getAreaId())) {//开放城市
								cityList1.add(cityBean);
							}
						}
						province1.setAreaId(province.getAreaId());
						province1.setAreaName(province.getAreaName());
						province1.setCities(cityList1);
					}
					continue;
				}
				if (!TextUtils.isEmpty(province1.getAreaId())) {
					mProvince.add(province1);
				}
			}
		} catch (Exception e) {
		}
		CLog.i(TAG, "准入城市=" + mProvince.toString());
		initCityAndDistrict(mProvince, mCity, mDistrict);
	}

	private static String readLocalJson(Context context, String fileName) {
		String resultString = "";
		InputStream inputStream = null;
		try {
			inputStream = context.getResources().getAssets().open(fileName);
			byte[] buffer = new byte[inputStream.available()];
			inputStream.read(buffer);
			resultString = new String(buffer, "utf-8");
			if (null != inputStream) {
				inputStream.close();
			}
		} catch (Exception e) {
		}
		return resultString;
	}

	/**
	 * 获取选项卡信息
	 */
	public static InitDataModel.Options getOptionList() {
		InitDataModel.Options bean = null;
		String optionsInfo = YJKD.getInstance().getPreferenceManager().getOptions();
		if (!TextUtils.isEmpty(optionsInfo) && !"{}".equals(optionsInfo)) {
			CLog.i(TAG, "选项卡信息=" + optionsInfo);
			Gson gson = new Gson();
			bean = gson.fromJson(optionsInfo, InitDataModel.Options.class);
		}
		return bean;
	}

	/**
	 * 判断是否是开放城市
	 *
	 * @param provinceList
	 * @param cityList
	 * @param countyList
	 * @param province
	 * @param city
	 * @param county
	 * @param type         默认为areaName、“areaId”表示根据areaId
	 * @return
	 */
	public static OpenCity judgeCity(ArrayList<AddressProvinceBean> provinceList, ArrayList<ArrayList<AddressCityBean>> cityList,
			ArrayList<ArrayList<ArrayList<AddressDistrictBean>>> countyList, String province, String city, String county, String type) {
		OpenCity result = new OpenCity();
		if (null == provinceList || null == cityList || null == countyList || TextUtils.isEmpty(province) || TextUtils.isEmpty(city)) {
			return null;
		}
		int provinceIndex = -1;
		int provinceSize = provinceList.size();
		for (int i = 0; i < provinceSize; i++) {
			if (("areaName".equals(type) && (provinceList.get(i).getAreaName().contains(province) || province.contains(provinceList.get(i).getAreaName())))
					|| ("areaId".equals(type) && (provinceList.get(i).getAreaId()).equals(province))) {
				result.province = provinceList.get(i).getAreaName();
				result.provinceCode = provinceList.get(i).getAreaId();
				provinceIndex = i;
				result.provinceIndex = provinceIndex;
				break;
			}
		}
		if (provinceIndex == -1) {
			return null;
		}
		int cityIndex = -1;
		int citySize = cityList.get(provinceIndex).size();
		for (int i = 0; i < citySize; i++) {
			if (("areaName".equals(type) && (cityList.get(provinceIndex).get(i).getAreaName().contains(city) || city.contains(cityList.get(provinceIndex).get(i).getAreaName())))
					|| ("areaId".equals(type) && (cityList.get(provinceIndex).get(i).getAreaId().equals(city)))) {
				result.city = cityList.get(provinceIndex).get(i).getAreaName();
				result.cityCode = cityList.get(provinceIndex).get(i).getAreaId();
				cityIndex = i;
				result.cityIndex = cityIndex;
				break;
			}
		}
		if (cityIndex == -1) {
			return null;
		}
		int countyIndex = -1;
		if (countyList.size() > 0) {
			int countySize = countyList.get(provinceIndex).get(cityIndex).size();
			if (!TextUtils.isEmpty(county)) {
				for (int i = 0; i < countySize; i++) {
					if (("areaName".equals(type) && (countyList.get(provinceIndex).get(cityIndex).get(i).getAreaName().contains(county) || county.contains(countyList.get(provinceIndex).get(cityIndex).get(i).getAreaName())))
							|| ("areaId".equals(type) && (countyList.get(provinceIndex).get(cityIndex).get(i).getAreaId().equals(county)))) {
						result.district = countyList.get(provinceIndex).get(cityIndex).get(i).getAreaName();
						result.districtCode = countyList.get(provinceIndex).get(cityIndex).get(i).getAreaId();
						countyIndex = i;
						result.districtIndex = countyIndex;
						break;
					}
				}
			}

			if (countyIndex == -1) {
				if(countySize > 0){
					result.districtCode = countyList.get(provinceIndex).get(cityIndex).get(0).getAreaId();
					result.districtIndex = 0;
				}else{
					result.districtCode = "";
					result.districtIndex = -1;
				}
			}
		}else{
			result.districtCode = "";
			result.districtIndex = -1;
		}
		return result;
	}

	public static class OpenCity {
		public String provinceCode;
		public String cityCode;
		public String districtCode;
		public int provinceIndex;
		public int cityIndex;
		public int districtIndex;
		public String province;
		public String city;
		public String district;

		public String getAddress() {
			return (province == null ? "" : province) + " " + (city == null ? "" : city) + " " + (district == null ? "" : district);
		}

		@Override
		public String toString() {
			return "OpenCity{" +
					"provinceCode='" + provinceCode + '\'' +
					", cityCode='" + cityCode + '\'' +
					", districtCode='" + districtCode + '\'' +
					", provinceIndex=" + provinceIndex +
					", cityIndex=" + cityIndex +
					", districtIndex=" + districtIndex +
					'}';
		}
	}
}